﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Data;
using System.Collections.Specialized;
using MonitorProvider.Prototype;
using FileMonitor.Configuration.Prototype;
using FileMonitor.Configuration.Providers;
using FileMonitor.Configuration.Prototype.BizProcess;
namespace TXTMonitor
{
    public class Process : FileMonitor.Service.Prototype.FileMonitorBase
    {

        #region FileMonitorBase Methods
        public override void ProcessChanged(FileSystemEventArgs e) { }
        
        public override void ProcessDeleted(FileSystemEventArgs e) { }

        public override void ProcessCreated(FileSystemEventArgs e)
        {
            try
            {
                string filename = e.Name;
                string filterPlantCode = base.baseConfiguration.FilterPlantCode;//this.AllConfig["FilterPlantCode"];
                string plantCode = this.GetPlantCodeFromFileName(e.Name);

                if (string.IsNullOrEmpty(filterPlantCode))
                {
                    ProcessFile(filename, e.FullPath);
                }
                else
                {
                    string[] filterPlants = filterPlantCode.Split(",".ToCharArray());
                    if (filterPlants != null)
                    {
                        if (filterPlants.Length == 0)
                        {
                            ProcessFile(filename, e.FullPath);
                        }
                        else
                        {
                            if (!filterPlantCode.Contains(plantCode))
                            {
                                ProcessFile(filename, e.FullPath);
                            }
                        }

                    }
                    else
                    {
                        ProcessFile(filename, e.FullPath);
                    }
                }

            }

            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion

    
        #region Private Method
        private void ProcessFile(string filename, string filePath)
        {
            string plantCode = GetPlantCodeFromFileName(filename);
           
            List<PlantProcessConfiguration> listPlantConfigs = ProviderService.GetPlantProcessConfigProvider().GetPlantProcessConfiguration(this.exchangeDB, plantCode, base.baseConfiguration.DataType);
            try
            {
                #region Defaut Process

                if (listPlantConfigs.Count == 0)
                {
                    DBProcess(null, plantCode, filename, filePath);
                }
                #endregion
                foreach (PlantProcessConfiguration plantConfig in listPlantConfigs)
                {

                    #region FTP Process
                    if (plantConfig.ProcessType == ProcessType.FTP)
                    {
                        FTPProcess(plantConfig, plantCode, filename, filePath);
                    }
                    #endregion

                    #region ExchangeDB Process
                    if (plantConfig.ProcessType == ProcessType.ExChangeDB)
                    {
                        DBProcess(plantConfig, plantCode, filename, filePath);
                    }
                    #endregion
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        private void DBProcess(PlantProcessConfiguration plantConfig, string plantCode, string filename, string filePath)
        {
            try
            {
                IProcessFile process = ProcessFactory.CreateProcess(ProcessType.ExChangeDB);
                ExcutedTask task = process.ProcessFile(plantConfig, base.baseConfiguration, plantCode, filename, filePath);
                NotifyTask(task);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        private void FTPProcess(PlantProcessConfiguration plantConfig, string plantCode, string filename, string filePath)
        {
            try
            {
                IProcessFile process = ProcessFactory.CreateProcess(ProcessType.FTP);

                ExcutedTask task = process.ProcessFile(plantConfig, base.baseConfiguration, plantCode, filename, filePath);
                NotifyTask(task);

            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

       
        #endregion

       
        #region Utility Method

        private string GetPlantCodeFromFileName(string FileName)
        {
            string plantCodeIndex = string.IsNullOrEmpty(base.baseConfiguration.PlantCodeIndex) ? "0" : base.baseConfiguration.PlantCodeIndex;
            string plantCodeLength = string.IsNullOrEmpty(base.baseConfiguration.PlantCodeLength) ? "4" : base.baseConfiguration.PlantCodeLength;
            string plantCode = FileName.Substring(Int32.Parse(plantCodeIndex), Int32.Parse(plantCodeLength));
            return plantCode;
        }

        #endregion

        
        #region Debug Data
        private List<string> CheckData(DataTable dtContent, DataTable dtSchema)
        {
            List<string> listErrCells = new List<string>();
            for (int i = 0; i < dtContent.Rows.Count; i++)
            {
                for (int j = 1; j < dtContent.Columns.Count; j++)
                {
                    int len = Int32.Parse(dtSchema.Rows[j][1].ToString());
                    if (len != -1)
                    {
                        if (dtContent.Rows[i][j].ToString().Length > len)
                        {
                            listErrCells.Add(i + "," + j);
                        }
                    }
                }
            }
            return listErrCells;
        }

        private DataTable GetSchema(string dtName, string connStr)
        {
            System.Data.SqlClient.SqlConnection conn = new System.Data.SqlClient.SqlConnection(connStr);
            conn.Open();
            string cmdtext = string.Format("select c.name,c.length from syscolumns c,systypes t,sysobjects o where t.xusertype=c.xtype and o.id=c.id and o.name='{0}' order by c.colid",dtName);
            DataTable dtSchema = new DataTable();
            System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand(cmdtext, conn);
            System.Data.SqlClient.SqlDataAdapter dap = new System.Data.SqlClient.SqlDataAdapter(cmd);
            DataSet ds = new DataSet();
            dap.Fill(ds);
            dtSchema = ds.Tables[0];
            conn.Close();
            return dtSchema;
        }
        #endregion
    }
}
